<template>
    <div class="table-page">
        <div class="table-search-box" @keyup.enter="search()">
            <div class="search-item">
                <label>科目：</label>
                <div class="table-query-input">
                    <category-select
                        :category-id.sync="queryData.categoryId"
                        :props="{}"
                    />
                </div>
            </div>

            <div class="search-item">
                <label>栏目类型：</label>
                <div class="table-query-input">
                    <el-select v-model="queryData.type" clearable placeholder="请选择">
                        <el-option
                            v-for="key in Object.keys(columnType)"
                            :key="key"
                            :label="columnType[key].desc"
                            :value="key"
                        >
                        </el-option>
                    </el-select>
                </div>
            </div>
            <div class="search-item">
                <label>名称：</label>
                <div class="table-query-input">
                    <el-input
                        v-model="queryData.searchKey"
                        clearable
                        placeholder="栏目名称"
                    ></el-input>
                </div>
            </div>
            <div class="search-item">
                <el-button
                    type="primary"
                    icon="el-icon-search"
                    :loading="tableLoading"
                    @click="clickSearch()"
                >搜索
                </el-button>
            </div>
            <div class="search-item">
                <el-button
                    icon="el-icon-refresh"
                    :loading="tableLoading"
                    @click="resetSearch()"
                >重置
                </el-button>
            </div>
        </div>
        <div class="table-operation-box">
            <el-button
                type="primary"
                plain
                style="margin-bottom: 2em"
                icon="el-icon-plus"
                @click="addColumn"
            >新增数据
            </el-button>
            <el-button
                type="danger"
                plain
                style="margin-bottom: 2em"
                icon="el-icon-delete"
                :disabled="selectDisable"
                @click="
                    tableDelete(
                        '/exam/column/deletes',
                        {
                            ids: tableSelect
                        },
                        true
                    )
                "
            >批量删除
            </el-button>
        </div>
        <div class="table-data-box">
            <el-table
                ref="table"
                v-loading="tableLoading"
                :data="tableData"
                border
                style="width: 100%;min-height:40em"
                row-key="id"
                @selection-change="tableSelectionChange"
            >
                <el-table-column type="selection" width="55" align="center">
                </el-table-column>
                <el-table-column
                    prop="categoryName"
                    label="科目名称"
                    min-width="100"
                ></el-table-column>

                <el-table-column
                    prop="name"
                    label="栏目名称"
                    width="200"
                ></el-table-column>
                <el-table-column prop="sort" label="排序" width="150">
                    <template
                        slot-scope="scope"
                        v-loading="scope.row.opLoading"
                    >
                        <div
                            v-show="!scope.row.sortEdit"
                            @dblclick="scope.row.sortEdit = true"
                        >
                            {{ scope.row.sort||0 }}
                        </div>
                        <el-input
                            v-show="scope.row.sortEdit"
                            v-model="scope.row.sort"
                            @blur="
                                sortEditSave(
                                    '/exam/column/change-sort',
                                    scope.row
                                )
                            "
                        ></el-input>
                    </template>
                </el-table-column>

                <el-table-column prop="name" label="栏目类型" width="200">
                    <template slot-scope="scope">
                        <k-tag :tag="columnType[scope.row.type]"></k-tag>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="dataCount"
                    label="章节数/试卷数"
                    width="120"
                ></el-table-column>
                <el-table-column
                    label="操作"
                    width="300"
                    align="center"
                    fixed="right"
                >
                    <template slot-scope="scope">
                        <el-button
                            v-if="!scope.row.edit"
                            :class="scope.row.show ? 'warning' : 'primary'"
                            type="text"
                            size="mini"
                            :icon="
                                scope.row.show
                                    ? 'el-icon-remove'
                                    : 'el-icon-circle-plus'
                            "
                            :loading="scope.row.opLoading"
                            @click="changeShow(scope.row)"
                        >{{ scope.row.show ? "隐藏" : "显示" }}
                        </el-button>
                        <el-button
                            v-if="!scope.row.edit && scope.row.name!='更多试卷'"
                            class="primary"
                            type="text"
                            size="mini"
                            icon="el-icon-edit"
                            :loading="scope.row.opLoading"
                            @click="editColumn(scope.row)"
                        >编辑
                        </el-button>
                        <el-button
                            v-if="!scope.row.edit && scope.row.name!='更多试卷'"
                            class="warning"
                            type="text"
                            icon="el-icon-delete"
                            size="mini"
                            :loading="scope.row.opLoading"
                            @click="
                                tableDelete(
                                    '/exam/column/delete',
                                    {
                                        id: scope.row.id
                                    },
                                    true
                                )
                            "
                        >删除
                        </el-button>
                        <el-button
                            v-if="scope.row.type !== 'randomFormPaper' && scope.row.type!=='specialPractice' && scope.row.name!='更多试卷'"
                            class="primary"
                            type="text"
                            size="mini"
                            icon="el-icon-edit"
                            :loading="scope.row.opLoading"
                            @click="convert(scope.row)"
                        >快捷转换
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div v-if="pageData.total" class="xy-between table-page-box">
            <el-pagination
                background
                :current-page.sync="pageData.currentPage"
                :page-sizes="pageData.pageSizes"
                :page-size.sync="pageData.pageSize"
                layout="total,  prev, pager, next, sizes, jumper"
                :total="pageData.total"
            >
            </el-pagination>
        </div>
        <el-dialog title="快捷转换" :visible.sync="converVisible" width="40%">
            <el-form :model="dataForm" label-width="6em">
                <el-form-item label="试卷类型" prop="paperTypes">
                    <el-select
                        v-model="paperForm.paperType"
                        clearable
                        placeholder="请选择"
                    >
                        <el-option
                            v-for="k in Object.keys(paperType)"
                            :key="k"
                            :label="paperType[k].desc"
                            :value="k"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="所属年份" prop="sourceYear">
                    <el-date-picker
                        v-model="paperForm.sourceYear"
                        type="year"
                        value-format="yyyy"
                        placeholder="选择年份"
                    >
                    </el-date-picker>
                </el-form-item>
                <el-form-item>
                    <el-button
                        :loading="converFlag"
                        type="success"
                        @click="convertData"

                    >确定
                    </el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
        <el-dialog
            :title="dialogFormTitle"
            :visible.sync="dialogFormVisible"
            custom-class="three-dialog"
            width="95%"
            @close="dialogC"
            @opened="openDialog"
        >
            <el-form
                ref="dataForm"
                :model="dataForm"
                label-width="6em"
                :rules="dataFormRule"
                class="table-edit-from"
            >
                <el-form-item label="选择科目" prop="name">
                    <category-select
                        :category-id.sync="dataForm.categoryId"
                        :is-disabled="dialogFormTitle === '栏目编辑'"
                        :props="{ clearable: false }"
                    />
                </el-form-item>
<!--                <el-form-item label="绑定平台" >
                    <el-select v-model="dataForm.groupId" filterable clearable placeholder="请选择平台">
                        <el-option
                            v-for="item in groupList"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                        </el-option>
                    </el-select>
                    不设置即为通用
                </el-form-item>-->
                <el-form-item label="快捷选择">
                    <el-radio-group v-model="quickSelection">
                        <el-radio label="章节练习">章节练习</el-radio>
                        <el-radio label="历年真题">历年真题</el-radio>
                        <el-radio label="模拟试卷">模拟试卷</el-radio>
                        <el-radio label="预测试卷">预测试卷</el-radio>
                        <el-radio label="冲刺密卷">冲刺密卷</el-radio>
                        <el-radio label="精华资料">精华资料</el-radio>
                        <el-radio label="精讲视频">精讲视频</el-radio>
                        <el-radio label="随机小测">随机小测</el-radio>
                        <el-radio label="随机小测">直播小课</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="栏目名称" prop="name">
                    <el-input v-model="dataForm.name"></el-input>
                </el-form-item>
                <el-form-item label="栏目位置">
                    <el-radio-group v-model="dataForm.position" >
                        <el-radio
                            v-for="key in Object.keys(columnPosition)"
                            :key="key"
                            :label="key"

                        >{{ columnPosition[key].desc }}
                        </el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="栏目属性">
                    <el-radio-group v-model="dataForm.type">
                        <el-radio
                            v-for="key in Object.keys(columnType)"
                            :key="key"
                            :label="key"
                            :disabled="disabled"
                        >{{ columnType[key].desc }}
                        </el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="其他科目">
                    <category-select
                        :category-id.sync="selectCategoryId"
                        :props="{ clearable: false }"
                    />
                </el-form-item>
                <el-form-item v-show="dataForm.type==='chapterPractice'" label="上级章节">
                    <el-cascader
                        v-loading="chapterFlag"
                        :show-all-levels="false"
                        clearable
                        filterable
                        :props="{
                                value: 'id',
                                label: 'name',
                                checkStrictly: true
                            }"
                        :options="chapterData"
                        @change="loadByParentChapter"
                    ></el-cascader>
                </el-form-item>
                <div
                    v-if="dataForm.type !== 'specialPractice'"
                    class="auto-grow el-form-item--medium"
                >
                    <h3
                        class="el-form-item__content el-form-item"
                        style="margin-left:1em;font-size: 18px;"
                    >
                        栏目配置
                    </h3>

                </div>
                <el-form-item v-if="dataForm.type === 'paperLibrary'">
                    <el-radio v-for="ptype in Object.keys(paperType)" v-model="paperTypes" :label="ptype">{{paperType[ptype].desc}}</el-radio>
                </el-form-item>
                <el-form-item v-if="dataForm.type === 'materialInfo'">
                    <el-radio v-for="mtype in Object.keys(materialType)" v-model="materialTypes" :label="mtype">{{materialType[mtype].desc}}</el-radio>
                </el-form-item>
                <el-form-item v-if="dataForm.type !== 'specialPractice'" class="edit_dev">
                    <el-transfer
                        v-model="dataForm.configs"
                        filterable
                        :titles="['列表', '选中']"
                        :button-texts="['到左边', '到右边']"
                        v-loading="loading"
                        :format="{
                            noChecked: '${total}',
                            hasChecked: '${checked}/${total}'
                         }"
                        :data="configData"
                        @change="changeConfig"
                        ref="transfer"
                    >
                        <div slot-scope="{ option }" style="display: flex;align-items: center;" :title="option.label">
                             <p style="width: 400px;overflow: hidden"> {{ option.label }}</p>
<!--                            v-if="dataForm.type!=='randomFormPaper'"-->
                            <el-switch

                                v-model="option.isFree"
                                active-color="#13ce66"
                                inactive-color="#ff4949"

                                active-text="免费"
                                inactive-text="付费"
                            >
                            </el-switch>
                            <el-input v-if="dataForm.type!=='randomFormPaper'" v-model="option.sort"  placeholder="排序"
                                      size="mini"
                                      style="width: 15%;margin-left: 5px"></el-input>
                        </div>
                        <!--                        <span slot-scope="{ option }">{{ option.key }} - {{ option.label }}</span>-->
                    </el-transfer>
                </el-form-item>
                <el-form-item>
                    <el-button  @click="sortChinese(true)">汉字排序</el-button>
                    <el-button  @click="sortChinese(false)">字段排序</el-button>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button :loading="submitFlag" @click="dialogC"
                >取 消</el-button
                >
                <el-button
                    :loading="submitFlag"
                    type="primary"
                    @click="
                        formDataSave(
                            '/exam/column/update-all',
                            saveDataCover,
                            () => {}
                        )
                    "
                >保 存</el-button
                >
            </span>
        </el-dialog>
    </div>
</template>

<script>
import {TablePage} from "@/layout/mixin/iVue.js";
import CategorySelect from "@/components/CategorySelect.vue";
import selectPage from "../component/selectPage.vue";
import {mapState} from "vuex";
import ChapterSelect from "@/components/ChapterSelect";
import {fetchDelete, get, post, put} from "@/api/request";
import {treeList2Tree} from "@/utils";
import {
    fetchConfigIdById,
    fetchPaper,
    fetchRule,
    fetchPaperId,
    fetchChapterById,
    fetchRuleId, fetchListPaper, fetchVideoList, fetchMaterialList, fetchList, fetchLiveList, fetchLiveId
} from "@/api/exam";

export default {
    name: "Column",
    components: {CategorySelect, selectPage, ChapterSelect},
    mixins: [TablePage],
    data() {
        return {
            paperForm: {
                paperType: [],

            },
            loading: false,
            paperTypes: null,
            materialTypes: null,
            configData: [],
            quickSelection: null,
            converVisible: false,
            selectCategoryId: null,
            selectChapterId: null,
            disabled: false,
            dataForm: {configs: [], name: "",position: "JGQY"},
            queryData: {
                searchKey: "",
                categoryId: null,
                type: null,
                haveCategoryName: true,
                haveDataCount: true
            },
            converFlag: false,
            initAddForm: {
                name: "",
                serverName: "",
                categoryId: null,
                type: "chapterPractice",
                sort: 100,
                configs: []
            },
            columnChildren: [],
            dataFormRule: {
                categoryId: [
                    {
                        required: true,
                        message: "请选择科目",
                        trigger: "change"
                    }
                ],
                name: [
                    {
                        required: true,
                        message: "请输入栏目名称",
                        trigger: "blur"
                    }
                ]
            },
            chapterId: null,
            change: false,
            columnTypeDefault: "",
            chapterData: [],
            version: 0,
            configsTemp: false,
            //科目数据
            tempdata1: [],
            //其它科目
            tempdata2: [],
            //存储已经选定的数据
            selectedMap: null,
        };
    },
    computed: {
        ...mapState({
            columnType: state => state.status.columnType,
            paperType: state => state.status.paperType,
            columnPosition: state => state.status.columnPosition,
            materialType: state => state.status.materialType
        }),
        settingTitle1() {
            if (this.dataForm.type === "chapterPractice") {
                return "章节";
            }
            if (this.dataForm.type === "paperLibrary") {
                return "试卷";
            }
            if (this.dataForm.type === "randomFormPaper") {
                return "规则";
            }
            return "";
        }
    },
    watch: {
        async "dataForm.type"() {
            if (this.configsTemp) {
                await this.selectCategory();

            }
        },
        async "paperTypes"() {
            if (this.configsTemp) {
                await this.findPaperOrRuleList(this.dataForm.type);
            }
        },
        async "materialTypes"() {
            if (this.configsTemp) {
                await this.findPaperOrRuleList(this.dataForm.type);
            }
        },
        "quickSelection"(val) {
            this.dataForm.name = val
        },
        "dataForm.configs"() {
            if (
                this.dataForm.configs !== undefined &&
                this.dataForm.configs !== null &&
                this.dataForm.configs.length > 0
            ) {
                this.disabled = true;
            } else {
                this.disabled = false;
            }
        },
        async "dataForm.categoryId"(val) {
            if (this.configsTemp) {
                await this.sCategory(1, val);

            }
        },
        async selectCategoryId(vl) {
            if (this.configsTemp) {
                await this.sCategory(2, vl);
            }
        },
    },
    created() {
        this.configsTemp = false

        this.selectedMap = new Map();
        this.loadGroupList();
    },
    methods: {
        search() {
            this.loadTable("/exam/column/page-admin", this.queryData);
        },
        changeConfig(value) {
            let selected = new Map()
            value.forEach(e => {
                let data = this.configData.filter(f => f.key === e)
                if (!selected.has(e)) {
                    selected.set(e, data[0])
                }
            })
            this.selectedMap = selected
        },
        openDialog() {
            this.$refs.transfer.clearQuery("left")
            this.$refs.transfer.clearQuery("right")

        },
        convert(data) {
            this.paperForm.columnId = data.id;
            if (data.type === "paperLibrary") {
                this.$confirm("是否将试卷转换为章节", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(() => {
                    let loading = this.$loading({
                        lock: true,
                        text: "Loading",
                        spinner: "el-icon-loading",
                        background: "rgba(0, 0, 0, 0.7)"
                    })
                    put("/exam/column/conver-chapter", this.paperForm).then(
                        res => {
                            if (res === true) {
                                this.$message.success("转换成功");
                                this.converVisible = false;
                                this.loadTable(
                                    "/exam/column/page",
                                    this.queryData
                                );

                            }
                            loading.close()
                        }
                    );
                });
            } else {
                this.converVisible = true;
            }
        },
        convertData() {
            this.converFlag = true
            put("/exam/column/conver-paper", this.paperForm).then(res => {
                if (res === true) {
                    this.$message.success("转换成功");
                    this.converVisible = false;
                    this.converFlag = false
                    this.loadTable("/exam/column/page", this.queryData);
                }
            });
        },
        dialogC() {
            this.configsTemp = false
            this.dialogFormVisible = false
        },
        sortChinese(sort){
            if(sort){
                this.configData.sort((item1,item2)=>{
                    return item1.label.localeCompare(item2.label,"zh-CN")
                })
            }else{
                this.configData.sort((item1,item2)=>{
                    return item1.sort-item2.sort
                })
            }

        },
        saveDataCover(data) {
            let morePaperData=this.configData
            if (data.type !== "specialPractice" && data.configs !== undefined && data.configs !== null) {
                for (let i = 0; i < data.configs.length; i++) {
                    if (data.configs[i].id === "") {
                        return this.$message.warning("请检查配置的数据是否为空");
                    }
                }
                let selectedArray = [...this.selectedMap.values()]
                console.log("selectedArray",selectedArray)
                console.log("this.configData",this.configData)
                data.configs = selectedArray.filter(m => m !== undefined && m !== null).map(
                    m => {
                   let temp= this.configData.filter(f=>f.key===m.key);
                    morePaperData=morePaperData.filter(f=>f.key!==m.key)
                    return {
                        id: m.key,
                        isFree: temp[0].isFree,
                        sort: temp[0].sort
                    }
                })
                data.moreConfigIds=morePaperData.filter(m => m !== undefined && m !== null).map(
                    m => {
                        return {
                            id: m.key,
                            isFree: m.isFree,
                            sort: m.sort
                        }
                    });
            }
            // // data 去重
            // if (!this.currentColumn) {
            //     let map3 = new Map();
            //     data.configs = data.configs.filter(
            //         key => !map3.has(key.id) && map3.set(key.id, 1)
            //     );
            // } else {
            //     delete data.configs
            // }

            return {
                ...data
            };
        },
        mergeConfig() {
            let selectedArray = [...this.selectedMap.values()]
            //console.log("selectedArray",selectedArray)
            //console.log("this.tempdata1",this.tempdata1)
            let removeDuplicate1 = this.removeDuplicate(this.tempdata1.concat(this.tempdata2).concat(selectedArray));
            let data = removeDuplicate1.map(f => {
                if (this.selectedMap.has(f.key)) {
                    f.sort = this.selectedMap.get(f.key).sort
                }
                return f;
            })
            data.sort((s1, s2) => {
                return s1.sort - s2.sort
            })
            return data
        },
        async editColumn(data) {
            let loading = this.$loading({
                lock: true,
                text: "Loading",
                spinner: "el-icon-loading",
                background: "rgba(0, 0, 0, 0.7)"
            })
            this.submitFlag = false;
            this.selectedMap = new Map();
            this.paperTypes = null;
            this.configData = [];
            this.selectCategoryId = null;
            this.columnTypeDefault = data.type;
            this.chapterData = [];
            this.tempdata2 = [];
            this.tempdata1 = [];
            let config = await fetchConfigIdById({id: data.id})
            data.configs = [];
            //console.log("this.dataForm",this.dataForm)
            this.dataForm = data;
            await this.sCategory(1, this.dataForm.categoryId, data.type);
            let temps = [];
            //console.log("this.configData",this.configData);
            for (let c of config) {
                let temp = this.configData.filter(f => f.key === c.configId)
                if (temp.length > 0) {
                    temp[0].sort = c.sort;
                    temp[0].isFree = c.isFree;
                    if (!this.selectedMap.has(temp[0].key)) {
                        this.selectedMap.set(temp[0].key, temp[0])
                    }
                } else {
                   // console.log(222)
                    let res = null
                    if (data.type === "paperLibrary") {
                        res = await fetchPaperId({id: c.configId})
                    }
                    if (data.type === "randomFormPaper") {
                        res = await fetchRuleId({id: c.configId})
                    }
                    if (data.type === "chapterPractice") {
                        res = await fetchChapterById({id: c.configId})
                        //this.chapterData = await this.loadTreeData(data.categoryId);

                    }
                    if (data.type === "video") {
                        res = await fetchVideoList({id: c.configId})
                        //this.chapterData = await this.loadTreeData(data.categoryId);
                        //console.log("chapter",this.chapterData)
                    }
                    if (data.type === "materialInfo") {
                        res = await fetchMaterialList({id: c.configId})
                        //this.chapterData = await this.loadTreeData(data.categoryId);
                        //console.log("chapter",this.chapterData)
                    }
                    if (data.type === "live") {
                        res = await fetchLiveId({id: c.configId})
                        //this.chapterData = await this.loadTreeData(data.categoryId);
                        //console.log("chapter",this.chapterData)
                    }
                    if (res !== null) {
                        let data = {
                            key: c.configId,
                            label: res.name===null?res.title:res.name,
                            sort: c.sort,
                            isFree: c.isFree
                        }
                        //console.log("chapter",data)
                        temps.push(data)
                        if (!this.selectedMap.has(data.key)) {
                            this.selectedMap.set(data.key, data)
                        }
                    }
                }
                this.dataForm.configs.push(c.configId)
            }
            this.configData = this.configData.concat(temps)
            this.configData.sort((s1, s2) => s1.sort - s2.sort)
            this.tempdata1 = this.configData
            this.clickSimpleEdit(data, "栏目编辑");
            this.configsTemp = true
            loading.close();
        },
        async findPaperOrRuleList(type) {

            if (type === "paperLibrary") {
                if (this.dataForm.categoryId !== null) {
                    this.tempdata1 = await this.selectPagerAll(this.dataForm.categoryId)
                }
                if (this.selectCategoryId !== null) {
                    this.tempdata2 = await this.selectPagerAll(this.selectCategoryId)
                }
            }
            if (type === "randomFormPaper") {
                if (this.dataForm.categoryId !== null) {
                    this.tempdata1 = await this.selectRandomFormPaperAll(this.dataForm.categoryId)
                }
                if (this.selectCategoryId !== null) {
                    this.tempdata2 = await this.selectRandomFormPaperAll(this.selectCategoryId)
                }

            }
            if (type === "video") {
                if (this.dataForm.categoryId !== null) {
                    this.tempdata1 = await this.selectVideoAll(this.dataForm.categoryId)
                }
                if (this.selectCategoryId !== null) {
                    this.tempdata2 = await this.selectVideoAll(this.selectCategoryId)
                }

            }
            if (type === "materialInfo") {
                if (this.dataForm.categoryId !== null) {
                    this.tempdata1 = await this.selectMaterialAll(this.dataForm.categoryId)
                }
                if (this.selectCategoryId !== null) {
                    this.tempdata2 = await this.selectMaterialAll(this.selectCategoryId)
                }
            }
            if (type === "live") {
                if (this.dataForm.categoryId !== null) {
                    this.tempdata1 = await this.selectLiveAll(this.dataForm.categoryId)
                }
                if (this.selectCategoryId !== null) {
                    this.tempdata2 = await this.selectLiveAll(this.selectCategoryId)
                }
            }
            this.configData = [...this.mergeConfig()]
            // this.configData.length=0;
            // for (let i = 0; i <this.mergeConfig().length ; i++) {
            //     this.$set(this.configData, i, this.mergeConfig()[i])
            // }
        },
        removeDuplicate(arr) {
            const map = new Map()
            const newArr = []
            arr.forEach(item => {
                if (!map.has(item.key)) { // has()用于判断map是否包为item的属性值
                    map.set(item.key, true) // 使用set()将item设置到map中，并设置其属性值为true
                    newArr.push(item)
                }
            })
            return newArr
        },
        addColumn() {
            this.chapterData = [];
            this.selectCategoryId = null;
            this.dataForm = {name: "",position: "JGQY"}
            this.initAddForm = {name: "",categoryId:this.queryData.categoryId,position: "JGQY"};
            this.quickSelection = null;
            this.configData = [];
            this.paperTypes = null
            this.selectedMap = new Map()
            this.clickAdd("添加栏目数据");
            this.configsTemp = true;
            this.submitFlag = false;
        }
        ,
        async sCategory(sw, vl) {
            if (sw === 1) {
                if (this.dataForm.type === "chapterPractice") {
                    let data = await this.loadTreeData(vl);
                    this.chapterData = data;
                    let dataArray = [];
                    data.forEach(m => {
                        dataArray.push({
                            key: m.id,
                            label: m.name,
                            disabled: false,
                            isFree: m.free,
                            sort: m.sort
                        })
                    })
                    this.tempdata1 = dataArray;
                } else if (this.dataForm.type === "paperLibrary") {
                    this.tempdata1 = await this.selectPagerAll(vl)
                } else if (this.dataForm.type === "randomFormPaper") {
                    this.tempdata1 = await this.selectRandomFormPaperAll(vl)
                } else if (this.dataForm.type === "video") {
                    this.tempdata1 = await this.selectVideoAll(vl)
                } else if (this.dataForm.type === "materialInfo") {
                    this.tempdata1 = await this.selectMaterialAll(vl)
                }else if (this.dataForm.type === "live") {
                    this.tempdata1 = await this.selectLiveAll(vl)
                }
            } else {
                if (this.dataForm.type === "chapterPractice") {
                    let data =  await this.loadTreeData(vl);
                    this.chapterData = await this.loadTreeData(vl);
                    this.tempdata2 = data;
                    this.tempdata2 = this.tempdata2.filter(f => f !== null && f !== undefined).map(m => {
                        return {
                            key: m.id,
                            label: m.name,
                            disabled: false,
                            isFree: m.free,
                            sort: m.sort
                        }
                    })
                } else if (this.dataForm.type === "paperLibrary") {
                    this.tempdata2 = await this.selectPagerAll(vl)
                } else if (this.dataForm.type === "randomFormPaper") {
                    this.tempdata2 = await this.selectRandomFormPaperAll(vl)
                }else if (this.dataForm.type === "video") {
                    this.tempdata2 = await this.selectVideoAll(vl)
                } else if (this.dataForm.type === "materialInfo") {
                    this.tempdata2 = await this.selectMaterialAll(vl)
                } else if (this.dataForm.type === "live") {
                    this.tempdata2 = await this.selectLiveAll(vl)
                }

            }
            this.configData = this.mergeConfig()
        }
        ,
        async selectRandomFormPaperAll(categoryId) {
            let tempArray = [];
            let params = {
                current: 1,
                size: 10000,
                pageSize: 10000,
                pageCurrent: 1,
                currentPage: 1,
                categoryId: categoryId
            };
            let res = await fetchRule(params);
            res.records.forEach(r => {
                tempArray.push({
                    key: r.id,
                    label: r.name,
                    disabled: false,
                    isFree:true,
                })
            })
            return tempArray
        },
        async selectPagerAll(categoryId) {
            this.loading = true
            let flag = true
            let temp = []
            let params = {
                current: 1,
                size: 300,
                pageSize: 300,
                pageCurrent: 1,
                currentPage: 1,
                categoryId: categoryId
            };
            if (this.paperTypes !== null) {
                params.paperType = this.paperTypes
            }
            //while (flag) {
            let res = await fetchList(params);

            res.forEach(f => {
                temp.push({
                    key: f.id,
                    label: f.name,
                    disabled: false,
                    isFree: f.free,
                    sort: f.sort

                })
            })
                // if (temp.length !== res.total) {
                //     params.current += 1
                // } else {
                //     flag = false
                // }

            //}
            //console.log("temp",temp)
            this.loading = false
            return temp
        },
        async selectVideoAll(categoryId) {
            let tempArray = [];
            let params = {
                categoryId: categoryId,
                parentId: 0
            };
            let res = await fetchVideoList(params);
            res.forEach(r => {
                tempArray.push({
                    key: r.id,
                    label: r.name,
                    disabled: false,
                    sort: r.sort,
                    isFree: false,
                })
            })
            return tempArray
        },
        async selectMaterialAll(categoryId) {
            let tempArray = [];
            let params = {
                categoryId: categoryId
            };
            // eslint-disable-next-line eqeqeq
            if(this.materialTypes != null ){
                params.materialType = this.materialTypes
            }
            let res = await fetchMaterialList(params);
            res.forEach(r => {
                tempArray.push({
                    key: r.id,
                    label: r.title,
                    disabled: false,
                    sort: r.sort,
                    isFree: false,
                })
            })
            //console.log("tempArray",tempArray)
            return tempArray
        },
        async selectLiveAll(categoryId) {
            let tempArray = [];
            let params = {
                categoryId: categoryId
            };
            // eslint-disable-next-line eqeqeq
            if(this.materialTypes != null ){
                params.materialType = this.materialTypes
            }
            let res = await fetchLiveList(params);
            res.forEach(r => {
                tempArray.push({
                    key: r.id,
                    label: r.title,
                    disabled: false,
                    sort: r.sort,
                    isFree: false,
                })
            })
            //console.log("tempArray",tempArray)
            return tempArray
        },
        async selectCategory() {
            //console.log("selectCategory");
            this.tempdata2 = [];
            this.tempdata1 = [];
            if (this.dataForm.type === "chapterPractice") {
                if (this.selectCategoryId !== null) {
                    let t2 = await this.loadTreeData(this.selectCategoryId);
                    this.tempdata2 = t2.filter(f => f !== null && f !== undefined).map(m => {
                        return {
                            key: m.id,
                            label: m.name,
                            disabled: false,
                            isFree: m.free,
                            sort: m.sort
                        }
                    })
                }
                if (this.dataForm.categoryId !== null) {
                    let t1 = await this.loadTreeData(this.dataForm.categoryId);
                    this.chapterData = t1;
                    this.tempdata1 = t1.filter(f => f !== null && f !== undefined).map(m => {
                        return {
                            key: m.id,
                            label: m.name,
                            disabled: false,
                            isFree: m.free,
                            sort: m.sort
                        }
                    })
                }
                this.configData = this.mergeConfig()
            } else {

                this.findPaperOrRuleList(
                    this.dataForm.type
                );
                // let arrayData = this.paperOrRuleOptions.concat(prData);
                // let map = new Map();
                // this.paperOrRuleOptions = arrayData.filter(
                //     key => key !== null ? (!map.has(key.id) && map.set(key.id, 1)) : false
                // );
            }
        }
        ,
        selectEvent(vl) {
            this.selectChapterId = vl;
            if (vl !== "") {
                for (let i = 0; i < this.dataForm.configs.length - 1; i++) {
                    if (this.dataForm.configs[i].id === vl) {
                        return this.$message.warning("添加的章节重复了");
                    }
                }
            }
        }
        ,
        async loadTreeData(id) {

            let categoryId = id;
            if (categoryId !== null) {
                return await get("/exam/chapter/list", {
                    categoryId,
                    size: 10000,
                    tree: false
                })
                    .then(res => {
                        return Promise.resolve(treeList2Tree(res));

                    })
                    .finally(() => {
                        this.version++;
                    });
            }
        }
        ,
        loadByParentChapter(node){

            let parentChapterId = node[node.length-1];
            if(parentChapterId === null || parentChapterId === undefined || parentChapterId === ""){
                return false;
            }
            get("/exam/chapter/list", {
                parentId: parentChapterId,
                size: 10000,
                tree: false
            })
                .then(res => {
                    this.tempdata1 = res.filter(f => f !== null && f !== undefined).map(m => {
                        return {
                            key: m.id,
                            label: m.name,
                            disabled: false,
                            isFree: m.free,
                            sort: m.sort
                        }
                    })
                    this.configData = [...this.mergeConfig()]
                })
                .finally(() => {
                    this.version++;
                });

        },
        changeShow(item) {
            this.itemEdit(
                item,
                put("/exam/column/update", {
                    id: item.id,
                    show: !item.show
                })
            ).then(() => {
                item.show = !item.show;
            });
        }
    }
}
;
</script>
<style>
.el-dialog.three-dialog .el-form .width-auto .el-select .el-input {
    width: 550px !important;
    max-width: 100% !important;
}


.search .width-auto .el-input {
    width: 440px !important;
    max-width: 100% !important;
}

.edit_dev .el-transfer-panel {
    width: 700px !important;
}
</style>
<style lang="scss" scoped>


.chapter {
    .chapter-line {
        margin-bottom: 22px;

        ::v-deep .el-form-item {
            margin-bottom: 0px;
        }
    }
}

.type-item {
    ::v-deep {
        .el-radio-group {
            display: grid;
            grid-template-columns: 1fr 1fr;
            width: 200px;
            grid-row-gap: 10px;
        }
    }
}
</style>
